import { Switch } from 'antd';
import { connect } from 'dva';
import moment from 'moment/moment';
import React from 'react';
import PropTypes from 'prop-types';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { AdvancedSearch, DATA_ENTRY, ContentPackage, IconC, InputNumberC, PrimaryC, TableC } from '@/src/comps';
import { namespace } from '@/src/newModels/marketAnalysis/BondDeviationMonitoringM';
import { exportFile, debounceFn } from '@/src/utils/commonFunc';
import { getColumnIntoWidth } from '@/src/utils/utils';
import styles from './index.less';

@Form.create()
@connect(({ loading, BondDeviationMonitoringM }) => ({
  loading,
  BondDeviationMonitoringM,
}))
class DayEndDeviationMonitoring extends React.PureComponent {
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
    pageType: '1',
  };

  constructor(props) {
    super(props);
    this.tenant = localStorage.getItem('antd-pro-tenant');
    this.state = {
      date: undefined, // 重置用
      bondType: '',
      netPriceDeviation: -2,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isPenetrate: true,
      dataSource: [],
      needPenetrate: '1', // 穿透工作台 是否穿透 默认是
      isMerge: true, // 穿透资产是否合并，默认true
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.pageType == '1') this.getTradeDay();
  }

  // 父组件调用
  settingAndSearch = (obj) => {
    const { tradingDate } = this.state;
    if (obj.date != tradingDate) {
      this.setState(
        {
          tradingDate: obj.date,
        },
        () => {
          this.dateRef?.setDate(moment(obj.date));
          this.getTableData();
        },
      );
    }
  };

  getTableData = () => {
    const { tradingDate, netPriceDeviation, currentPage, isPenetrate, needPenetrate, bondType, isMerge } = this.state;
    const { dispatch, pageType } = this.props;
    const payload =
      pageType == 2
        ? {
            date: tradingDate,
            netPriceDeviation: netPriceDeviation || '',
            isPenetrate: needPenetrate == 1 ? 0 : 1,
            Page: currentPage,
            pageSize: 99999,
            tenant: this.tenant,
            bondType: bondType || '',
          }
        : {
            date: tradingDate,
            netPriceDeviation: netPriceDeviation || '',
            Page: currentPage,
            pageSize: 99999,
            isPenetrate: isPenetrate === true ? 0 : 1,
            tenant: this.tenant,
            bondType: bondType || '',
            isMerge: isMerge === true ? '0' : '1',
          };
    // console.log('payload111', payload);
    dispatch({
      type: `${namespace}/queryDayMonitor`,
      payload,
      callback: (res) => {
        this.setState({
          dataSource: res.data.dataSource,
          total: res.data.pageInfo.total || res.data.dataSource.length,
        });
      },
    });
  };

  searchDocker = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    const { tradingDate } = this.state;
    let date;
    if (e) {
      date = moment(e.date).format('YYYY-MM-DD');
      this.setState(
        {
          tradingDate: date,
          needPenetrate: e.needPenetrate,
          bondType: e.bondType,
        },
        () => this.getTableData(),
      );
    } else {
      date = moment(this.state.date).format('YYYY-MM-DD');
      setFieldsValue({ netPriceDeviation: -2 });
      this.dateRef?.setDate(moment(this.state.date).add(0, 'days'));
      this.setState(
        {
          tradingDate: date,
          netPriceDeviation: -2,
          isPenetrate: true,
          bondType: '',
          isMerge: true,
        },
        () => this.getTableData(),
      );
    }
  };

  // 修改净价偏离度
  changeNetPriceDeviation = (e) => {
    this.setState(
      {
        netPriceDeviation: e,
      },
      () => {
        if ((e || e === 0) && e !== '-' && typeof e === 'number') {
          this.getTableData();
        }
      },
    );
  };

  // 持仓穿透处理
  PositionPenetration = (isPenetrate) => {
    this.setState(
      {
        isPenetrate,
      },
      () => this.getTableData(),
    );
  };

  // 穿透资产是否合并
  handleChangeMSwitch = (e) => {
    // console.log('e', e);
    this.setState(
      {
        isMerge: e,
      },
      () => this.getTableData(),
    );
  };

  // 导出
  exportContent = () => {
    const { tradingDate, netPriceDeviation, isPenetrate, bondType, needPenetrate, isMerge } = this.state;
    const { pageType } = this.props;
    const payload = {
      date: tradingDate,
      netPriceDeviation,
      isPenetrate: isPenetrate === true ? 0 : 1,
      tenant: this.tenant,
      isMerge: isMerge === true ? '0' : '1',
    };
    // console.log('payload222', payload);
    if (bondType) payload.bondType = bondType;
    if (pageType == '2') payload.isPenetrate = needPenetrate == 1 ? 0 : 1; // 穿透工作台的是否穿透
    exportFile('gateway/instrument-server/bondDeviationAnalysis/exportDayEndDeviationAnalysisInfo', payload);
  };

  // 换页
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      pageSize,
    });
  };

  // 获取前一交易日
  getTradeDay = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/getTradingDate`,
      payload: { type: '1' },
      callback: (res) => {
        this.setState(
          {
            tradingDate: moment(res).format('YYYY-MM-DD'),
            date: moment(res).format('YYYY-MM-DD'),
          },
          () => {
            this.getTableData();
          },
        );
      },
    });
  };

  // 查询模块
  searchForm = () => {
    const { pageType, parentId } = this.props;
    const { tradingDate } = this.state;
    return (
      <AdvancedSearch
        parentId={parentId}
        onQuery={(e) => {
          this.searchDocker(e);
        }}
        onClear={(e) => {
          this.searchDocker(e);
        }}
        dataSource={[
          {
            dataIndex: 'date',
            title: pageType == '2' ? '查询日期' : '截止日期',
            type: DATA_ENTRY.SINGLEDATE,
            initialValue: moment(tradingDate).add(0, 'days'),
            disableEnd: moment(new Date()).add(-1, 'days'),
            onRef: (ref) => (this.dateRef = ref),
            allowClear: false,
            useDisabledDate: { calendarType: 2 },
          },
          {
            dataIndex: 'needPenetrate',
            title: '是否穿透',
            type: DATA_ENTRY.SELECT,
            isTrueFalseJudge: true,
            initialValue: '1',
            hide: pageType != '2',
          },
          {
            dataIndex: 'bondType',
            title: '债券类型',
            allowClear: true,
            type: DATA_ENTRY.SELECT,
            // hide: pageType == '2',
            dataSource: [
              {
                title: '利率债',
                value: 'rate',
              },
              {
                title: '信用债',
                value: 'credit',
              },
            ],
          },
        ]}
      />
    );
  };

  // 查询模块
  searchInfo = () => {
    const { form, pageType } = this.props;
    return (
      <div className={styles.operateBottom}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <IconC title='此处监控结果针对持有产品的相关持仓' type='info' />
          <div className={styles.operateMiddle}>
            <span>净价偏离度=（每日最低成交净价-中债估值净价）/中债估值净价&lt;</span>
            <InputNumberC
              dataIndex='netPriceDeviation'
              precision={2}
              form={form}
              initialValue={-2}
              rules={[{ required: true, message: ' ' }]}
              onChange={(e) => debounceFn(this.changeNetPriceDeviation, e)}
            />
            <span>%</span>
          </div>
        </div>
        <div className={styles.exportSwitch}>
          {pageType != 2 ? (
            <div className={styles.changeSwitch}>
              <span>持仓穿透</span>
              <Switch defaultChecked={true} onChange={(e) => debounceFn(this.PositionPenetration, e)} />
              <div style={{ display: this.state.isPenetrate ? 'flex' : 'none' }}>
                <span>穿透资产是否合并</span>
                <Switch defaultChecked={this.state.isMerge} onChange={(e) => debounceFn(this.handleChangeMSwitch, e)} />
              </div>
            </div>
          ) : null}
          <PrimaryC style={{ marginLeft: 20 }} onClick={this.exportContent} title='导出' />
        </div>
      </div>
    );
  };

  // 表格模块
  renderTable = () => {
    const {
      loading,
      pageType,
      BondDeviationMonitoringM: { columns },
    } = this.props;
    const { dataSource, currentPage, pageSize, total } = this.state;
    const columnIntoWidth = getColumnIntoWidth(columns, dataSource);
    return (
      <div id='testTableId'>
        <TableC
          columns={columnIntoWidth || []}
          loading={loading.effects[`${namespace}/queryDayMonitor`]}
          dataSource={dataSource || []}
          scroll={pageType == 2 ? { x: 'max-content', y: 380 } : { x: 'max-content' }}
          rowKey='id'
          current={currentPage}
          pageSize={pageSize}
          total={total}
          selfScrollY={pageType == 1}
          onChange={this.handleTableChange}
          size='small'
        />
      </div>
    );
  };

  render() {
    const { pageType } = this.props;
    return (
      <>
        {pageType == '2' ? (
          <div className={styles.BondDeviationMonitoring}>
            {this.searchForm()}
            {this.searchInfo()}
            {this.renderTable()}
          </div>
        ) : (
          <ContentPackage
            title='日终偏离监控'
            contentHtml={
              <div className={styles.BondDeviationMonitoring}>
                {this.searchForm()}
                {this.searchInfo()}
                {this.renderTable()}
              </div>
            }
          />
        )}
      </>
    );
  }
}
// props默认值
DayEndDeviationMonitoring.propsTypes = {
  pageType: PropTypes.string, // pageType=1时，表示在主功能页面；pageType=2时，表示在穿透工作台；
  date: PropTypes.string, // type=2时，可传入默认查询日期YYYY-MM-DD
};
export default DayEndDeviationMonitoring;
